# coding=utf-8

from . import business
from flask import request, redirect, render_template, send_file
from app import util
from dbConnection.MysqlConn import Mysql
from app.MySession import MySession
import urllib, time
import qrcode
from io import BytesIO

# 商家登陆
@business.route('/business/login.html')
def business_login():
    return 'op'


# 商家登陆处理
@business.route('/business/login_post', methods=['post'])
def login_post():
    data = {}
    try:
        username = request.values.get('username')
        password = request.values.get('password')
        user = get_business(username)
        if user is None:
            data['code'] = 400
            data['msg'] = '用户不存在'
            return util.to_json(data)
        if user['status'] == 0:
            data['code'] = 401
            data['msg'] = '账号已禁用'
            return util.to_json(data)
        if util.md5(str(password)) != user['password']:
            data['code'] = 402
            data['msg'] = '密码错误'
            return util.to_json(data)
        user_session = MySession.create_session(str(user['bid']))
        data['code'] = 200
        data['msg'] = '登陆成功'
        data['session_id'] = user_session
        data['nickname'] = user['nickname']
        update_user_login(user['bid'])
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 商户修改密码
@business.route('/business/update_pass', methods=['post'])
@util.business_verify
def update_pass(uid):
    data = {}
    data['code'] = 400
    data['msg'] = '操作失败'
    try:
        new_pass = request.values.get('new_pass')
        password = request.values.get('password')
        if new_pass == password:
            data['code'] = 401
            data['msg'] = '老密码不能跟新密码相同'
            return util.to_json(data)
        user = get_uid_detail(uid)
        if user is None:
            return redirect('/business/login.html')
        if user['password'] != util.md5(str(password)):
            data['code'] = 402
            data['msg'] = '老密码错误'
            return util.to_json(data)
        res = update_user_pass(uid, new_pass)
        if res > 0:
            data['code'] = 200
            data['msg'] = '修改成功'
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 生成商家赠送二维码
# @business.route('/business/buy_wash_code', methods=['post'])
# @util.business_verify
# def buy_wash_code(uid):
#     data = {}
#     data['code'] = 400
#     data['msg'] = '订单不存在'
#     try:
#         pid = request.values.get('pid')
#         order_business = get_order_detail(uid, pid)
#         if order_business is None:
#             return util.to_json(data)
#         if order_business['use_num'] >= order_business['num']:
#             data['code'] = 401
#             data['msg'] = '订单没有剩余次数'
#             return util.to_json(data)
#         res = add_buy_log(order_business)
#         if res > 0:
#             data['code'] = 200
#             data['msg'] = '获取成功'
#             data['url'] = urllib.quote(business_url(uid, res))
#             update_orders(pid, uid)
#     except Exception as e:
#         print e
#         data['code'] = 500
#         data['msg'] = '系统错误'
#     return util.to_json(data)


# 用户领取
@business.route('/business/user_receive', methods=['post'])
def user_receive():
    data = {}
    data['code'] = 400
    data['msg'] = '领取失败'
    try:
        openid = request.values.get('opneid')
        bid = request.values.get('bid')
        gid = request.values.get('gid')
        user = get_user_detail(openid)
        if user is None:
            data['code'] = 401
            data['msg'] = '用户不存在'
            return util.to_json(data)
        give_log = get_business_give(bid, gid)
        if give_log is None:
            data['code'] = 402
            data['msg'] = '记录不存在'
            return util.to_json(data)
        if give_log['uid'] > 0:
            data['code'] = 403
            data['msg'] = '洗车卷已领取'
            return util.to_json(data)
        res = add_user_taocan(user['uid'], give_log['rid'], gid, bid)
        if res > 0:
            update_sj_give_log(user['uid'], gid, res, bid)
            data['code'] = 200
            data['msg'] = '领取成功'
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


@business.route('/business/qrcode/send', methods=['POST', 'GET'])
def business_qrcode():
    content = request.values.get('data')
    qr = qrcode.QRCode(
            version=3,  # 生成二维码尺寸的大小 1-40 1:21*21（21+(n-1)*4）
            error_correction=qrcode.constants.ERROR_CORRECT_M,  # L:7% M:15% Q:25% H:30%
            box_size=6,  # 每个格子的像素大小
            border=2,  # 边框的格子宽度大小
    )
    qr.add_data(content)
    img = qr.make_image()
    byte_io = BytesIO()
    img.save(byte_io, 'PNG')
    byte_io.seek(0)
    return send_file(byte_io, mimetype='image/png')


# 更新商家赠送记录
def update_sj_give_log(uid, gid, tid, bid):
    sql = "update business_give_log SET uid = '%s', tid = '%s' WHERE id = '%s' AND bid = '%s'" % (uid, tid, gid, bid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    return res


# 用户领取洗车卷
def add_user_taocan(uid, rid, gid, bid):
    tc = get_recharge_detail(rid)
    if tc is None:
        return 0
    end_time = int(time.time()) + int(tc['stopTime']) * 86400
    end_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time))
    sql = "insert INTO user_taocan(uid, recharge_id, recharge_num, end_time, order_id, recharge_name, give_uid, " \
          "source_type, add_time) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', 2, now())" % (uid, rid, tc['num'],
                                                                                                  end_str, gid,
                                                                                                  tc['name'], bid)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 获取套餐信息
def get_recharge_detail(rid):
    sql = "select * FROM recharge WHERE id = '%s'" % rid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取赠送信息
def get_business_give(bid, gid):
    sql = "select * FROM business_give_log WHERE id = '%s' AND bid = '%s'" % (gid, bid)
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取用户信息
def get_user_detail(openid):
    sql = "select * FROM car_users WHERE wxOpenId = '%s'" % openid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 二维码
def business_url(bid, gid):
    url_str = "http://gz.deyiauto.com/wash/success.html?bid=%s&gid=%s" % (bid, gid)
    wx_str = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx087bed01c194a785&redirect_uri=%s" \
             "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect" % urllib.quote(url_str)
    return wx_str


# 更新商家订单
def update_orders(pid, uid):
    sql = "update business_pay_log SET use_num = use_num + 1 WHERE id = '%s' AND bid = '%s'" % (pid, uid)
    mysql = Mysql()
    mysql.update(sql, None)
    mysql.dispose()


# 生成商家赠送记录
def add_buy_log(data):
    sql = "insert INTO business_give_log(bid, pid, rid, add_time) VALUES ('%s', '%s', '%s', now())" % \
          (data['bid'], data['id'], data['recharge_id'])
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 查询商家订单
def get_order_detail(uid, pid):
    sql = "select * FROM business_pay_log WHERE id = '%s' AND bid = '%s'" % (pid, uid)
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 更新用户登陆信息
def update_user_login(uid):
    ip = request.headers.get('X-Real-Ip', request.remote_addr)
    sql = "update user_business SET login_time = now(), login_num = login_num + 1, login_ip = '%s' WHERE " \
          "bid = '%s'" % (ip, uid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()


# 获取用户
def get_business(username):
    sql = "select * FROM user_business WHERE username = '%s'" % username
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取用户信息
def get_uid_detail(uid):
    sql = "select * FROM user_business WHERE bid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 更新用户密码
def update_user_pass(uid, password):
    sql = "update user_business SET password = '%s' WHERE bid = '%s'" % (util.md5(str(password)), uid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    return res
